import { vw } from "@/common/dimensions";
import globalStyles from "@/common/styles/globalStyles";
import BottomModal from "@/components/BottomModal";
import IconButton from "@/components/IconButton";
import IconTextButton from "@/components/IconTextButton";
import LazyImage from "@/components/LazyImage";
import TextButton from "@/components/TextButton";
import { UserImgItemType, userImgListAtom, userImgParamsAtom } from "@/store/user";
import { useAtom } from "jotai";
import React, { useState } from "react";
import { GestureResponderEvent, Pressable, ScrollView, StyleSheet, Text, View } from "react-native";
import * as ImagePicker from 'expo-image-picker';
import { uploadFileServer } from "@/servers/app-servers";
import Toast from "react-native-toast-message";
import { useUserImgList } from "@/hooks/useUserImgList";

export default function FooterButton(props: {
	onPressCreate: (event: GestureResponderEvent) => void;
}) {
	const [userImgParams] = useAtom(userImgParamsAtom)
	let { onPressCreate } = props;
	// 存储制作按钮高度
	const [viewHeight, setViewHeight] = useState(0);
	// 底部弹出层是否显示
	const [bottomVisible, setBottomVisible] = useState(false);


	const selectImage = () => {
		setBottomVisible(true);
	};

	const onLayout = (e: any) => {
		const { height } = e.nativeEvent.layout;
		setViewHeight(height);
	};

	return (
		<View
			style={[
				globalStyles.rowLine,
				globalStyles.aiCenter,
				{ marginVertical: 24 },
			]}
		>
			<View style={{ flex: 1, marginRight: 24 }} onLayout={onLayout}>
				<TextButton
					buttonText="一键制作"
					backgroundColor="#fff272"
					onPress={onPressCreate}
				></TextButton>
			</View>
			<View>
				<IconButton
					path={userImgParams.full_path}
					size={viewHeight}
					onPress={selectImage}
				/>
			</View>
			<BottomModal
				bottomModalVisible={bottomVisible}
				bottomModalProps={{
					children: (
						<BottomModalChildren hideModal={() => {
							setBottomVisible(false);
						}} />
					),
					hideModal: () => {
						setBottomVisible(false);
					},
				}}
			></BottomModal>
		</View>
	);
}

const BottomModalChildren = (props: { hideModal: Function }) => {
	let { hideModal } = props

	// 用户图片数据
	const [ ImgParam, setImgParams] = useAtom(userImgParamsAtom)
	// 当前用户图片
	const [userImgList, setUserImgList] = useAtom(userImgListAtom);
	// 用户图片数据
	const [userImgParams, setUserImgParams] = useAtom(userImgParamsAtom);
	// 更新用户图片列表
    const { getUserImgList} = useUserImgList();



	const verifyPermissions = async () => {
		const { status: cameraStatus } = await ImagePicker.requestCameraPermissionsAsync();
		if (cameraStatus !== 'granted') {
			Toast.show({
				type:'error',
				text1:"抱歉, 需要权限才能访问相机!"
			})
			return;
		}

		const { status: mediaLibraryStatus } = await ImagePicker.requestMediaLibraryPermissionsAsync();
		if (mediaLibraryStatus !== 'granted') {
			Toast.show({
				type:"error",
				text1:"抱歉, 需要权限才能访问相册!"
			})
		  	return;
		}
	}
	// 打开相册
	const openAlbum = async () => {
		await verifyPermissions()
		// 打开相册
		let result = await ImagePicker.launchImageLibraryAsync({
			mediaTypes: ImagePicker.MediaTypeOptions.Images, // 仅选择图片
			allowsEditing: true, // 允许用户编辑图片
			aspect: [1, 1], // 设置裁剪框的宽高比
			quality: 1, // 图片质量 (1 为最高质量)
		});
		if (!result.canceled) {
			uploadFile(result.assets[0].uri)
		}
	}
	// 打开相机
	const openCamera = async () =>{
		await verifyPermissions()
		const result = await ImagePicker.launchCameraAsync({
			mediaTypes: ImagePicker.MediaTypeOptions.Images, // 仅限图片
			allowsEditing: true, // 允许编辑图片
			aspect: [1, 1], // 裁剪比例
			quality: 1, // 图片质量（1为最高）
		});
		if (!result.canceled) {
			uploadFile(result.assets[0].uri)
		}
		
		
	}

	const uploadFile = async (path:string) => {
		let formData = new FormData();
		// 获取文件名
		const fileName = path.split('/').pop();
		// 获取文件扩展名（可选）
		const fileType = fileName?.split('.').pop();
		formData.append('file', {
			uri: path,
			name: fileName,
			type: `image/${fileType}` || 'image/jpeg', // 默认使用 image/jpeg
		} as any); // 注意：TS 需要使用 `as any` 类型转换，避免类型冲突
		const res = await uploadFileServer(formData)
		const { code , data } = res
		if(code === 0 && data){
			let {url} = data
			if(url){
				Toast.show({
					type:"success",
					text1:"上传成功",
				})
				await getUserImgList()
				hideModal()
			}
		}
	}

	


	const changeUserImgData = (value: UserImgItemType) => {
		setImgParams(value)
		hideModal()
	}
	return (
		<View>
			<View style={[globalStyles.rowLine, globalStyles.jcSB , {paddingBottom:24}]}>
				<View style={{ width: "46%" }}>
					<IconTextButton
						iconPath={require("@/assets/createTask/album.png")}
						iconSize={16}
						buttonText="相册"
						type="row"
						backgroundColor="#fff7c0"
						onPress={openAlbum}
					/>
				</View>
				<View style={{ width: "46%" }}>
					<IconTextButton
						iconPath={require("@/assets/createTask/camera.png")}
						iconSize={16}
						buttonText="相机"
						type="row"
						backgroundColor="#fff7c0"
						onPress={openCamera}
					/>
				</View>
			</View>
			<ScrollView >
				<View style={[{ marginTop: 24, flexWrap: "wrap" , paddingBottom:100  }, globalStyles.rowLine ]}>
					{
						userImgList.map(item => (
							<Pressable 
								onPress={() => changeUserImgData(item)} 
								key={item.id}
							>
								<LazyImage
									uri={item.full_path}
									style={[styles.userImg, item.id === userImgParams.id && styles.activeUserImg ]}
									defaultSource={require('@/assets/common/perch.png')}
								/>
							</Pressable>
						))
					}
				</View>
			</ScrollView>
			
			<Toast />
		</View>
	);
};

const styles = StyleSheet.create({
	userImg: {
		width: 29.99 * vw,
		height: 30 * vw,
		borderRadius: 12,
		marginBottom: 1 * vw,
		marginHorizontal:1 * vw 
	},
	activeUserImg:{
		borderWidth:2,
		borderColor:"#007acc"
	}
})
